<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-card">
        <div class="login-header">
          <h2>{{ isLogin ? '登录' : '注册' }}</h2>
          <p>{{ isLogin ? '欢迎回来' : '创建新账号' }}</p>
        </div>
        
        <!-- 登录表单 -->
        <div v-if="isLogin" class="login-form-container">
          <!-- 用户名密码登录表单 -->
          <el-form
            v-if="!showMobileLogin"
            :model="loginForm"
            :rules="loginRules"
            ref="loginFormRef"
            class="login-form"
            label-width="0"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="用户名"
                prefix-icon="User"
                size="large"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="密码"
                prefix-icon="Lock"
                size="large"
                show-password
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="login-btn"
                @click="handleLogin"
                :loading="loading"
                block
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 手机号码登录表单 -->
          <el-form
            v-if="showMobileLogin"
            :model="mobileLoginForm"
            :rules="mobileLoginRules"
            ref="mobileLoginFormRef"
            class="login-form"
            label-width="0"
          >
            <el-form-item prop="username">
              <el-input
                v-model="mobileLoginForm.username"
                placeholder="手机号码"
                prefix-icon="Phone"
                size="large"
              />
            </el-form-item>
            
            <!--<el-form-item prop="code">-->
              <!--<div class="code-input-group">-->
                <!--<el-input-->
                  <!--v-model="mobileLoginForm.code"-->
                  <!--placeholder="验证码"-->
                  <!--prefix-icon="Key"-->
                  <!--size="large"-->
                  <!--class="code-input"-->
                <!--/>-->
                <!--<div class="captcha-container">-->
                  <!--<canvas-->
                    <!--ref="captchaCanvas"-->
                    <!--class="captcha-canvas"-->
                    <!--@click="refreshCaptcha"-->
                    <!--title="点击刷新验证码"-->
                  <!--&gt;</canvas>-->
                <!--</div>-->
              <!--</div>-->
            <!--</el-form-item>-->
              <el-form-item prop="password">
                  <el-input
                          v-model="mobileLoginForm.password"
                          type="password"
                          placeholder="密码"
                          prefix-icon="Lock"
                          size="large"
                          show-password
                  />
              </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="login-btn"
                @click="handleMobileLogin"
                :loading="loading"
                block
              >
                手机号码登录
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 切换按钮 -->
          <div class="switch-container">
            <el-button
              type="text"
              @click="showMobileLogin = !showMobileLogin"
              class="switch-btn"
            >
              {{ showMobileLogin ? '用户名登录' : '手机号码登录' }}
            </el-button>
          </div>
        </div>
        
        <!-- 注册表单 -->
        <el-form
          v-if="!isLogin"
          :model="registerForm"
          :rules="registerRules"
          ref="registerFormRef"
          class="login-form"
          label-width="0"
        >
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="手机号码"
              prefix-icon="Phone"
              size="large"
            />
          </el-form-item>
          
                     <el-form-item prop="code">
             <div class="code-input-group">
               <el-input
                 v-model="registerForm.code"
                 placeholder="验证码"
                 prefix-icon="Key"
                 size="large"
                 class="code-input"
               />
               <div class="captcha-container">
                 <canvas
                   ref="registerCaptchaCanvas"
                   class="captcha-canvas"
                   @click="refreshRegisterCaptcha"
                   title="点击刷新验证码"
                 ></canvas>
               </div>
             </div>
           </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="设置密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="确认密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-btn"
              @click="handleRegister"
              :loading="loading"
              block
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>
        

        
        <div class="login-footer">
          <p>{{ isLogin ? '还没有账号？' : '已有账号？' }}</p>
          <el-button
            type="text"
            @click="isLogin = !isLogin"
            class="register-link"
          >
            {{ isLogin ? '立即注册' : '立即登录' }}
          </el-button>
        </div>
        
        <!--<div class="demo-accounts">-->
          <!--<h4>演示账号</h4>-->
          <!--<div class="account-list">-->
            <!--<div class="account-item">-->
              <!--<span>管理员：</span>-->
              <!--<span>admin / 123456</span>-->
            <!--</div>-->
            <!--<div class="account-item">-->
              <!--<span>业务员A：</span>-->
              <!--<span>sales001 / 123456</span>-->
            <!--</div>-->
            <!--<div class="account-item">-->
              <!--<span>业务员B：</span>-->
              <!--<span>sales002 / 123456</span>-->
            <!--</div>-->
          <!--</div>-->
        <!--</div>-->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { login, mobileLogin, register, getInfo, getRouters } from "@/api/login"

const router = useRouter()
const userStore = useUserStore()

const loginFormRef = ref()
const mobileLoginFormRef = ref()
const registerFormRef = ref()
const captchaCanvas = ref()
const registerCaptchaCanvas = ref()
const loading = ref(false)
const isLogin = ref(true)
const showMobileLogin = ref(false)

// 验证码数据
const captchaData = ref({
  login: { text: '', canvas: null },
  register: { text: '', canvas: null }
})

// 登录表单
const loginForm = ref({
  username: 'admin',
  password: 'admin123'
})

// 手机号码登录表单
const mobileLoginForm = ref({
  username: '',
  code: '',
  password: '',
})

// 注册表单
const registerForm = ref({
  username: '',
  code: '',
  password: '',
  confirmPassword: ''
})

// 登录验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 手机号码登录验证规则
const mobileLoginRules = {
  username: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码为4位字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 注册验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码为4位字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 生成图形验证码
const generateCaptcha = (canvas, type) => {
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  const width = canvas.width
  const height = canvas.height
  
  // 清空画布
  ctx.clearRect(0, 0, width, height)
  
  // 生成随机验证码（4位数字和字母组合）
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let captchaText = ''
  for (let i = 0; i < 4; i++) {
    captchaText += chars[Math.floor(Math.random() * chars.length)]
  }
  
  // 保存验证码文本
  captchaData.value[type].text = captchaText
  
  // 设置背景
  ctx.fillStyle = '#f0f0f0'
  ctx.fillRect(0, 0, width, height)
  
  // 添加干扰线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`
    ctx.beginPath()
    ctx.moveTo(Math.random() * width, Math.random() * height)
    ctx.lineTo(Math.random() * width, Math.random() * height)
    ctx.stroke()
  }
  
  // 添加干扰点
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`
    ctx.fillRect(Math.random() * width, Math.random() * height, 2, 2)
  }
  
  // 绘制验证码文字
  ctx.font = 'bold 40px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  
  // 计算文字间距，确保在容器中居中
  const totalWidth = 4 * 30 // 4个字符，每个间距30px
  const startX = (width - totalWidth) / 2 + 15 // 居中起始位置
  
  for (let i = 0; i < captchaText.length; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 100 + 50},${Math.random() * 100 + 50},${Math.random() * 100 + 50})`
    ctx.save()
    ctx.translate(startX + i * 30, height / 2)
    ctx.rotate((Math.random() - 0.5) * 0.15)
    ctx.fillText(captchaText[i], 0, 0)
    ctx.restore()
  }
}

// 刷新登录验证码
const refreshCaptcha = () => {
  if (captchaCanvas.value) {
    generateCaptcha(captchaCanvas.value, 'login')
  }
}

// 刷新注册验证码
const refreshRegisterCaptcha = () => {
  if (registerCaptchaCanvas.value) {
    generateCaptcha(registerCaptchaCanvas.value, 'register')
  }
}

// 获取用户信息
const getUserInfo = async () => {
  const userInfo = await getInfo()
  const routeInfo = await getRouters()

  userStore.setUser(userInfo)
  userStore.setRoute(routeInfo)

  ElMessage.success('登录成功')
  router.push('/')
}

// 用户名登录
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    loading.value = true

    const userObj = await login(loginForm.value)
    const userData = {
      token: userObj.token
    }
    userStore.setToken(userData)
    getUserInfo()
  } catch (error) {
    ElMessage.error('请完善登录信息')
  } finally {
    loading.value = false
  }
}

// 手机号码登录
const handleMobileLogin = async () => {
  try {
    await mobileLoginFormRef.value.validate()
    
    // 验证图形验证码
    if (mobileLoginForm.value.code.toUpperCase() !== captchaData.value.login.text) {
      ElMessage.error('验证码错误')
      return
    }
    
    loading.value = true

    const userObj = await login(mobileLoginForm.value)
    const userData = {
      token: userObj.token
    }
    userStore.setToken(userData)
    getUserInfo()
  } catch (error) {
    ElMessage.error('请完善登录信息')
  } finally {
    loading.value = false
  }
}

// 注册
const handleRegister = async () => {
  try {
    await registerFormRef.value.validate()
    
    // 验证图形验证码
    if (registerForm.value.code.toUpperCase() !== captchaData.value.register.text) {
      ElMessage.error('验证码错误')
      return
    }
    
    loading.value = true

    await register(registerForm.value)
    ElMessage.success('注册成功，请登录')
    isLogin.value = true
    showMobileLogin.value = false
    registerForm.value = {
      username: '',
      code: '',
      password: '',
      confirmPassword: ''
    }
  } catch (error) {
    ElMessage.error('注册失败，请重试')
  } finally {
    loading.value = false
  }
}

// 组件挂载后生成验证码
onMounted(async () => {
  await nextTick()
  refreshCaptcha()
  refreshRegisterCaptcha()
})
</script>

<style scoped>
    :deep(.el-form-item__content) {
        justify-content: center;
    }

    .login-btn {
        width: 200px;
    }

    .code-input-group {
        display: flex;
        gap: 15px;
        align-items: center;
    }

    .code-input {
        flex: 1;
    }

    .captcha-container {
        width: 130px;
        height: 40px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        overflow: hidden;
        cursor: pointer;
        background: #f5f7fa;
    }

    .captcha-canvas {
        width: 100%;
        height: 100%;
        display: block;
        scale: calc(2)
    }

    .login-form-container {
        margin-bottom: 20px;
    }

    .switch-container {
        text-align: center;
        margin: 20px 0;
    }

    .switch-btn {
        color: #667eea;
        font-size: 14px;
    }

.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 400px;
}

.login-card {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin: 0 0 10px 0;
  font-size: 28px;
}

.login-header p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.login-form {
  margin-bottom: 20px;
}

.login-footer {
  text-align: center;
  margin-bottom: 30px;
}

.login-footer p {
  color: #666;
  margin: 0 0 10px 0;
  font-size: 14px;
}

.register-link {
  color: #667eea;
  text-decoration: none;
  font-weight: bold;
}

.register-link:hover {
  text-decoration: underline;
}

.demo-accounts {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.demo-accounts h4 {
  color: #333;
  margin: 0 0 15px 0;
  font-size: 16px;
  text-align: center;
}

.account-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.account-item {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  padding: 5px 0;
}

.account-item span:first-child {
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
  }
  
  .login-header h2 {
    font-size: 24px;
  }

  .code-input-group {
    flex-direction: column;
  }

  .captcha-container {
    width: 100%;
    height: 70px;
  }
}
</style> 